import { DTO } from "./constant";

function createValidate(fn: any) {
  return (message: string) => {
    return (target: Object, key: string) => {
      const arr = Reflect.getMetadata(DTO, target) || []

      arr.push({
        fn,
        message,
        key
      })

      Reflect.defineMetadata(DTO,  arr, target)
    }
  }
}

export const IsNoEmpty = createValidate((val: any) => {
  return val != null && val !== ''
})


export function validate(data: any, dto: any) {
  const metadata = Reflect.getMetadata(DTO, dto)

  if (Array.isArray(metadata)) {
    const errors = metadata.map(({ fn, message, key }) => {
      const valid = fn(data[key])

      return {
        message,
        key,
        valid
      }
    }).filter((t) => !t.valid)

    return errors
  }
  return  []
}